package com.titaniume.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ProjectName: juc
 * @Package: com.titaniume.lock
 * @ClassName: ThreadDemo2
 * @Author: huangrenfei
 * @Description: 线程直接的通信 交替改变变量的值 Lock 实现
 * @Date: 2021/11/22 13:52
 * @Version: 1.0
 */

//  第一步 创建资源类，在资源类创建属性和操作方法
class Share {

    //初始化值
    private int number = 0;

    //创建Lock
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    //+1
    public void incr() {
        //上锁
        lock.lock();
        try {
            //判断
            if (number != 0) {
                condition.await();
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName() + " ::" + number);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }

    //-1
    public void decr() {
        //上锁
        lock.lock();
        try {
            //判断
            if (number != 1) {
                condition.await();
            }
            //干活
            number--;
            System.out.println(Thread.currentThread().getName() + " ::" + number);
            //通知
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }


}

public class ThreadDemo2 {

    public static void main(String[] args) {
        //   第三步 创建多线程，调用资源类的操方法
        Share share = new Share();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.incr();
            }
        },"AA").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.decr();
            }
        },"BB").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.incr();
            }
        },"CC").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                share.decr();
            }
        },"DD").start();
    }
}



